﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using EPiServer.Core;
using PageTypeBuilder;
using TemplateFoundation.Core;

namespace TemplateFoundation.Reflection
{
    /// <summary>
    /// Helpers for working with type inheritance
    /// </summary>
    public class Inheritance
    {
        static Inheritance()
        {
            // Find the website's main assembly
            if(PageReference.IsNullOrEmpty(PageReference.StartPage) || PageReference.StartPage==PageReference.RootPage)
            {
                return;
            }

            // Get assembly of website based on the type of the start page
            SiteAssembly = PageTypeResolver.Instance.GetPageTypeType(PageReference.StartPage.GetPage().PageTypeID).Assembly;
        }

        /// <summary>
        /// Gets or sets the site assembly.
        /// </summary>
        /// <value>The site assembly.</value>
        public static Assembly SiteAssembly { get; private set; }

        /// <summary>
        /// Gets all types inheriting from the specified base type
        /// </summary>
        /// <param name="baseType"></param>
        /// <returns></returns>
        protected static IEnumerable<Type> FindDerivedTypes(Type baseType)
        {
            return FindDerivedTypes(null, baseType);
        }

        /// <summary>
        /// Returns all types inheriting from the specified base type
        /// </summary>
        /// <param name="baseType"></param>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static IEnumerable<Type> FindDerivedTypes(Assembly assembly, Type baseType)
        {
            if (assembly==null)
            {
                assembly = SiteAssembly;
            }

            return assembly.GetTypes().Where(baseType.IsAssignableFrom);
        }
    }
}
